package address

import (
	"context"
	"encoding/json"
	"errors"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteAddressLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteAddressLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteAddressLogic {
	return &DeleteAddressLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteAddressLogic) DeleteAddress(req *types.DeleteAddressReq) (resp *types.Reply, err error) {

	userId, _ := l.ctx.Value("userId").(json.Number).Int64()

	address, err := l.svcCtx.Db.FindAddrById(userId, req.Id)

	if err != nil {
		return nil, err
	}

	if address.Default {
		return nil, errors.New("默认地址不能删除")
	}

	if err := l.svcCtx.Db.DeleteAddr(address); err != nil {
		return nil, err
	}

	return nil, nil
}
